#!/usr/bin/env python3
"""
从数据库提取真实的搜索关键词
"""

from app import create_app
from app.services.civil_code_service import CivilCodeService
from collections import Counter
import re

def extract_keywords():
    """提取真实关键词"""
    app = create_app()
    
    with app.app_context():
        try:
            service = CivilCodeService()
            
            # 基于统计信息的编章关键词
            stats = service.get_statistics()
            articles_by_part = stats.get('articles_by_part', {})
            
            print("=== 基于编章的关键词 ===")
            part_keywords = []
            for part, count in articles_by_part.items():
                # 提取编章中的关键词
                keywords = extract_part_keywords(part)
                part_keywords.extend(keywords)
                print(f"{part}: {keywords} ({count}条)")
            
            # 常见法律搜索词汇
            common_legal_terms = [
                '合同', '物权', '婚姻', '继承', '人格权', '侵权', 
                '民事权利', '债权', '担保', '抵押', '所有权',
                '违约', '损害赔偿', '法人', '自然人', '监护',
                '代理', '诉讼时效', '不动产', '动产', '知识产权'
            ]
            
            print("\n=== 测试关键词搜索效果 ===")
            effective_keywords = []
            
            for keyword in common_legal_terms:
                try:
                    result = service.smart_search(keyword, per_page=1)
                    articles = result.get('articles', [])
                    if articles:  # 如果有搜索结果
                        effective_keywords.append(keyword)
                        print(f"✓ {keyword}: 有效")
                    else:
                        print(f"✗ {keyword}: 无结果")
                except Exception as e:
                    print(f"✗ {keyword}: 错误 - {e}")
            
            # 生成最终的搜索建议
            print(f"\n=== 最终搜索建议 ===")
            
            # 优先级关键词（基于编章）
            priority_keywords = ['合同', '物权', '婚姻', '继承', '人格权', '侵权']
            
            # 合并有效关键词
            final_suggestions = []
            
            # 添加优先级关键词
            for keyword in priority_keywords:
                if keyword in effective_keywords:
                    final_suggestions.append(keyword)
            
            # 添加其他有效关键词
            for keyword in effective_keywords:
                if keyword not in final_suggestions and len(final_suggestions) < 12:
                    final_suggestions.append(keyword)
            
            # 如果关键词不够，添加组合词
            if len(final_suggestions) < 12:
                compound_terms = [
                    '合同纠纷', '物权保护', '婚姻家庭', '继承权', 
                    '人格权保护', '侵权责任', '民事权利', '债权债务',
                    '担保物权', '损害赔偿', '诉讼时效', '不动产登记'
                ]
                for term in compound_terms:
                    if len(final_suggestions) < 12:
                        final_suggestions.append(term)
            
            print("搜索建议列表:")
            for i, suggestion in enumerate(final_suggestions, 1):
                print(f"  {i}. {suggestion}")
            
            # 生成热门搜索数据
            print(f"\n=== 热门搜索数据 ===")
            popular_tags = []
            for i, keyword in enumerate(final_suggestions[:8]):
                # 模拟搜索计数（基于编章法条数量）
                base_count = 100 + i * 50
                popular_tags.append({
                    'keyword': keyword,
                    'count': format_count(base_count),
                    'trending': i < 3  # 前3个标记为热门
                })
                
            for tag in popular_tags:
                trend = "🔥" if tag['trending'] else ""
                print(f"  {tag['keyword']}: {tag['count']} {trend}")
            
            return {
                'search_suggestions': final_suggestions[:6],  # 快捷搜索6个
                'popular_tags': popular_tags[:6]  # 热门搜索6个
            }
            
        except Exception as e:
            print(f"提取失败: {str(e)}")
            import traceback
            traceback.print_exc()
            return None

def extract_part_keywords(part_name):
    """从编章名称提取关键词"""
    keyword_map = {
        '总则': ['民事权利', '法人', '自然人'],
        '物权': ['物权', '所有权', '担保'],
        '合同': ['合同', '债权', '违约'],
        '人格权': ['人格权', '隐私权'],
        '婚姻家庭': ['婚姻', '家庭', '监护'],
        '继承': ['继承', '遗产'],
        '侵权责任': ['侵权', '损害赔偿']
    }
    
    for key, keywords in keyword_map.items():
        if key in part_name:
            return keywords
    return []

def format_count(count):
    """格式化计数显示"""
    if count >= 1000:
        return f"{count//1000:.1f}k"
    return str(count)

if __name__ == '__main__':
    result = extract_keywords()
    if result:
        print(f"\n=== 生成的数据结构 ===")
        print(f"搜索建议: {result['search_suggestions']}")
        print(f"热门标签: {result['popular_tags']}")

